<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\Api;

use App\Middleware\JwtMiddleware;
use App\Model\Feedback;
use App\Model\User;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;

#[Controller]
class FeedbackController
{
    #[Inject]
    protected ValidatorFactoryInterface $validationFactory;
    #[Inject]
    protected RequestInterface $request;

    #[Middleware(JwtMiddleware::class)]
    #[RequestMapping(path: "", methods: "post")]
    /**
     * 详情
     * @return false|string
     */
    public function add()
    {
        $data = $this->validationFactory->make(
            $this->request->all(),
            [
                'content' => 'required',
                'img_ids' => '',
                'username' => '',
                'mobile' => ''
            ],
            [
                'content.required' => '请填写反馈内容'
            ]
        );

        if ($data->fails()) {
            return self::jsonResponse(422, $data->errors()->first());
        }

        $data = $data->validated();
        if (($data['img_ids'] ?? '') && is_string(($data['img_ids'] ?? ''))) {
            $data['img_ids'] = explode(',', $data['img_ids']);
        }

        $imgIds = $data['img_ids'] ?? [];
        unset($data['img_ids']);

        /** @var User $user */
        $user = auth()->user();
        $feedback = new Feedback($data);
        $feedback->user()->associate($user);
        $feedback->save();

        $feedback->imgs()->sync($imgIds);

        return self::jsonResponse(200, 'success');
    }

    public static function jsonResponse(int $status = 1, $message = 'success', $data = null, $headerStatus = 200)
    {
        if (is_array($message)) {
            $data = $message;
            $message = 'success';
        }
        if (empty($data)) {
            $data = new class {
            };
        }

        return json_encode(['status' => $status, 'message' => $message, 'data' => $data]);

//        return response()->json(
//            ['status' => $status, 'message' => $message, 'data' => $data],
//            $headerStatus,
//            [],
//            JSON_UNESCAPED_UNICODE
//        );
    }
}
